package com.xxx.util;

import com.xxx.config.exception.GenExceptCode;
import com.xxx.config.exception.ServiceException;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FileUtil {

    /**
     * 获取文件的contentType
     *
     * @param fileName 文件名
     * @return contentType
     */
    public static String getContentType(String fileName) {
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String result;
        fileType = fileType.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = "image/png";
        } else if (fileType.endsWith(".gif")) {
            result = "image/gif";
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = "image/jpeg";
        } else if (fileType.endsWith(".svg")) {
            result = "image/svg+xml";
        } else if (fileType.endsWith(".doc")) {
            result = "application/msword";
        } else if (fileType.endsWith(".xls")) {
            result = "application/x-excel";
        } else if (fileType.endsWith(".zip")) {
            result = "application/zip";
        } else if (fileType.endsWith(".pdf")) {
            result = "application/pdf";
        } else {
            result = "application/octet-stream";
        }
        return result;
    }


    /**
     * 保存inputStream到文件
     *
     * @param inputStream inputStream
     * @param filePath    文件全路径
     * @return File
     */
    public static File saveFile(InputStream inputStream, String filePath) {
        File file = new File(filePath);
        return save(inputStream, file);
    }

    /**
     * 保存inputStream到文件
     *
     * @param inputStream inputStream
     * @param file        file
     * @return File
     */
    public static File saveFile(InputStream inputStream, File file) {
        return save(inputStream, file);
    }

    private static File save(InputStream inputStream, File file) {
        OutputStream outputStream = null;
        try {
            outputStream = Files.newOutputStream(file.toPath());

            // 保存文件
            Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new ServiceException(GenExceptCode.System_Error.name(), "文件上传失败！");
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (Exception e) {
                //
            }
        }
        return file;
    }

}
